/* Simple drag and drop implementation for table rows */
(function() {
  window.SimpleSortable = function(element, options) {
    const container = element;
    const opts = options || {};
    let draggedElement = null;
    let placeholder = null;

    function createPlaceholder() {
      const ph = document.createElement('tr');
      ph.className = 'sortable-placeholder';
      ph.style.height = '40px';
      ph.style.background = 'rgba(79, 70, 229, 0.1)';
      ph.style.border = '2px dashed rgba(79, 70, 229, 0.3)';
      ph.innerHTML = '<td colspan="100%" style="text-align: center; color: var(--primary-color);">拖拽到此处</td>';
      return ph;
    }

    function handleDragStart(e) {
      draggedElement = this;
      this.style.opacity = '0.5';
      
      if (opts.ghostClass) {
        this.classList.add(opts.ghostClass);
      }

      e.dataTransfer.effectAllowed = 'move';
      e.dataTransfer.setData('text/html', this.outerHTML);
    }

    function handleDragEnd(e) {
      this.style.opacity = '';
      
      if (opts.ghostClass) {
        this.classList.remove(opts.ghostClass);
      }

      // Clean up
      const placeholders = container.querySelectorAll('.sortable-placeholder');
      placeholders.forEach(ph => ph.remove());

      draggedElement = null;
      placeholder = null;
    }

    function handleDragOver(e) {
      if (e.preventDefault) {
        e.preventDefault();
      }

      e.dataTransfer.dropEffect = 'move';
      return false;
    }

    function handleDragEnter(e) {
      if (this === draggedElement) return;

      // Remove existing placeholder
      if (placeholder && placeholder.parentNode) {
        placeholder.parentNode.removeChild(placeholder);
      }

      // Create new placeholder
      placeholder = createPlaceholder();
      
      // Insert placeholder
      const rect = this.getBoundingClientRect();
      const midpoint = rect.top + rect.height / 2;
      
      if (e.clientY < midpoint) {
        this.parentNode.insertBefore(placeholder, this);
      } else {
        this.parentNode.insertBefore(placeholder, this.nextSibling);
      }
    }

    function handleDrop(e) {
      if (e.stopPropagation) {
        e.stopPropagation();
      }

      if (draggedElement !== this && placeholder) {
        // Get indices
        const rows = Array.from(container.children);
        const oldIndex = rows.indexOf(draggedElement);
        const newIndex = rows.indexOf(placeholder);

        // Move element
        if (placeholder.nextSibling) {
          container.insertBefore(draggedElement, placeholder.nextSibling);
        } else {
          container.appendChild(draggedElement);
        }

        // Remove placeholder
        placeholder.remove();

        // Call onEnd callback
        if (opts.onEnd) {
          opts.onEnd({
            oldIndex: oldIndex,
            newIndex: newIndex > oldIndex ? newIndex - 1 : newIndex,
            item: draggedElement
          });
        }
      }

      return false;
    }

    // Initialize
    function init() {
      const rows = container.querySelectorAll('tr[data-rule-id]');
      
      rows.forEach(row => {
        const handle = row.querySelector(opts.handle || '.drag-handle');
        if (handle) {
          row.draggable = true;
          row.addEventListener('dragstart', handleDragStart);
          row.addEventListener('dragend', handleDragEnd);
          row.addEventListener('dragover', handleDragOver);
          row.addEventListener('dragenter', handleDragEnter);
          row.addEventListener('drop', handleDrop);
        }
      });
    }

    // Public methods
    return {
      init: init,
      destroy: function() {
        const rows = container.querySelectorAll('tr[data-rule-id]');
        rows.forEach(row => {
          row.draggable = false;
          row.removeEventListener('dragstart', handleDragStart);
          row.removeEventListener('dragend', handleDragEnd);
          row.removeEventListener('dragover', handleDragOver);
          row.removeEventListener('dragenter', handleDragEnter);
          row.removeEventListener('drop', handleDrop);
        });
      }
    };
  };
})();